package org.yray.tts.dic;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DictFactory {

    private final Map<Long,WordDict> dictMap=new ConcurrentHashMap<>();
    private static  DictFactory singleInstance;

    private DictFactory ()
    {

    }


    public static synchronized  DictFactory getInstance() {
        if (null == singleInstance) {
            singleInstance = new DictFactory();
            singleInstance.initGlobalDict();
        }
        return singleInstance;
    }

    //这里线程不安全，由外层来控制
    public void clean(Long key)
    {
        WordDict wordDict=dictMap.remove(key);
        if(wordDict!=null)
        {
            wordDict.clean();
        }
    }

    /***
     * 这个加入分词
     * @param word
     * @param key
     */
    public void addWord(String word,Long key)
    {
        WordDict wordDict=getWordDict(key);
        String[] words= word.split(RegexUtils.SPILT_ALL_2);
        for(String w:words) {
            wordDict.addWord(w);
        }
    }

    public void addWord(Long key,String word)
    {
        WordDict wordDict=getWordDict(key);
        wordDict.addWord(word);
    }

    public void initGlobalDict()
    {
        WordDict wordDict=getWordDict(0);
        wordDict.loadDict();
    }
    public void normalize(Long key)
    {
        WordDict wordDict=getWordDict(key);
        wordDict.normalize();
    }

    public WordDict getWordDict(long key)
    {
        return dictMap.computeIfAbsent(key,v->new WordDict());
    }

    public DictSegment getTrie(Long key)
    {
        WordDict wordDict=getWordDict(key);
        return wordDict.getTrie();
    }
}
